<?php
namespace admin\service;

use admin\models\Manager;
use admin\service\interfaces\IMenuService;
use common\service\CommonService;
use herosphp\cache\CacheFactory;
use herosphp\core\Loader;

Loader::import('admin.service.interfaces.IMenuService');

/**
 * 管理后台菜单服务
 * @package admin\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class MenuService extends CommonService implements IMenuService {


    /**
     * @see IMenuService::updateMenuCache
     */
    public function updateMenuCache()
    {
        $items = $this->where(array('ishow' => 1))->sort(array('sort_num' => 1))->find();
        foreach ( $items as $key => $value ) {
            $items[$key]['subs'] = $this->where(array('pid' => $value['id'], 'ishow' => 1))->sort(array('sort_num' => 1))->find();
        }
        $cacheHandler = CacheFactory::create('file');
        $cacheHandler->set(self::MANAGER_MENU_CACHE_KEY, $items, 0); //永久缓存
    }

    /**
     * @see IMenuService::getMenuByPermission
     */
    public function getMenuByPermission(Manager $manager)
    {
        $cacheHandler = CacheFactory::create('file');
        $data = $cacheHandler->get(self::MANAGER_MENU_CACHE_KEY);
        if ( $data == false ) {
            $this->updateMenuCache();
            $data = $cacheHandler->get(self::MANAGER_MENU_CACHE_KEY);
        }

        //根据权限过滤菜单
        foreach ( $data as $key => $value ) {
            foreach ( $value['subs'] as $k => $v ) {
                if ( !$manager->hasPermission($v['url']) ) {
                    unset($value['subs'][$k]);
                }
            }
            if ( count($value['subs']) == 0 ) {
                unset($data[$key]);
            }
        }
        return $data;
    }
}
